package com.carrot.api.controller.system;

import com.carrot.common.core.controller.BaseController;
import com.carrot.common.core.domain.AjaxResult;
import com.carrot.common.core.domain.dto.PointProtocolDto;
import com.carrot.common.core.domain.vo.PointProtocolIecVo;
import com.carrot.common.core.domain.vo.PointProtocolIecVoV2;
import com.carrot.common.core.domain.vo.PointProtocolMqttVo;
import com.carrot.common.exception.ServiceException;
import com.carrot.common.utils.StringUtils;
import com.carrot.system.service.IPointParserService;
import jakarta.annotation.security.PermitAll;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

/**
 * 点表解析
 */
@RestController
@RequestMapping("/system/point-parser")
public class SysPointParserController extends BaseController {

    @Autowired
    private IPointParserService pointParserService;

    /**
     * IEC104
     *
     * @param dto
     * @return
     */
    @PermitAll
    @PostMapping("iec104")
    public AjaxResult iec104(@RequestBody PointProtocolDto dto) {
        if (StringUtils.isEmpty(dto.getMessage())) {
            throw new ServiceException("参数校验失败");
        }
        // 转成list
        PointProtocolIecVo iecVo = pointParserService.iec104(dto.getMessage().trim());

        return AjaxResult.success(iecVo);
    }

    @PermitAll
    @PostMapping("iec104v2")
    public AjaxResult iec104v2(@RequestBody PointProtocolDto dto) {
        if (StringUtils.isEmpty(dto.getMessage())) {
            throw new ServiceException("参数校验失败");
        }
        // 转成list
        String[] array = dto.getMessage().split("\n");
        List<String> messages = Arrays.asList(array);
        PointProtocolIecVoV2 iecVo = pointParserService.iec104v2(dto.getDataset(), messages);

        return AjaxResult.success(iecVo);
    }

    /**
     * MQTT
     *
     * @param dto
     * @return
     */
    @PermitAll
    @PostMapping("mqtt")
    public AjaxResult mqtt(@RequestBody PointProtocolDto dto) {
        if (StringUtils.isAnyEmpty(dto.getTopic(), dto.getMessage())) {
            throw new ServiceException("参数校验失败");
        }
        PointProtocolMqttVo mqttVo = pointParserService.mqtt(dto.getTopic(), dto.getMessage());
        return AjaxResult.success(mqttVo);
    }
}
